define(['moment'], function (moment) {
    return ['$scope', '$filter', '$mdDialog', 'config', 'MMWService', '$calculater', '$gallery', '$timeout',
        function ($scope, $filter, $mdDialog, config, $MMWService, $calculater, $gallery, $timeout) {
            $scope.init = function () {
                $scope.qc_page = 'first_check';
                $scope.condition = {
                    op_no : '',
                    op_name: '',
                    op_display : '',
                    machine_no : '',
                    plot: ''
                };

                var settings = JSON.parse(localStorage.getItem(config.appName + '_B0502_favourite_op_no')||'{}');
                $scope.condition.op_no = settings.op_no||'';
                $scope.condition.op_name = settings.op_name||'';
                $scope.condition.plot_no = '';
                if($scope.condition.op_no != ''){
                    $scope.condition.op_display = settings.op_no + ' ('+settings.op_name+')';
                }
                $scope.inspectionInfo_list = {
                    checklist_detail: []
                };
            };

            $scope.back = function () {
                $scope.$root.hideMenu();
                $scope.$root.changeProgram('home', true);
            };

            $scope._fn = {
                favorite: {
                    click: function(name, callback) {

                        if(config.setting.OperatingArea==''){
                            $scope.$root.showAlert($filter('translate')('home.showAlert'));
                            return;
                        }
                        $MMWService.showQueryListPNIG({
                            form_name: 'PageNo_33',
                            mode:'M',
                            key:'page_no',
                            header : [
                                {label: $filter('translate')('common.queryList.op_c'), code:'page_no'},
                                {label: $filter('translate')('common.queryList.op_n'), code:'page_name'}
                            ],
                            selectKey:{key:'favourite', true:'1', false:'0'},
                            setCondition:function(conditions){
                                conditions.push({column_name:'B.MASTERNO', query_mode:'0', value:config.setting.OperatingArea, merge_condition_model:'AND' });
                                return conditions;
                            },
                            confirm: function(selectItem, dialog){
                                var content = {
                                    master_type: 5,
                                    master_no :config.setting.OperatingArea,
                                    favourite_qc_op_detail:[]
                                };
                                if(selectItem && selectItem.length>0){
                                    selectItem.forEach(function(item){
                                        if(item.favourite == '1'){
                                            content.favourite_qc_op_detail.push({op_no:item.page_no});
                                        }
                                    });
                                }
                                beforeSaveFavorite(content.favourite_qc_op_detail, function(){
                                    $MMWService.sendToServer({
                                        uri: 'ServicesSTD.Module_SYS.favourite_machine_process',
                                        content : content,
                                        success : function(data){
                                            dialog.hide();
                                            $scope.$root.showToast($filter('translate')('B0214_F.msg.saveSucess'));
                                            if(callback)
                                                callback();
                                        }
                                    });
                                });
                            }
                        });
                    }
                },
                Execute: {
                    click: function(name) { 
                        $scope.confirm();
                    }
                }
            };

            $scope.$watch('inspectionInfo', (newVal, oldVal) => {
                let isDisable = !newVal ? 'Y' : 'N';
                $scope._fn['Execute'].isDisabled = isDisable;
                $scope._event['inspection_info'].isDisabled = isDisable;
                $scope._event['machine_no'].isDisabled = isDisable;
                $scope._event['work_machine'].isDisabled = isDisable;
                $scope._event['pcs_no'].isDisabled = isDisable;
            });

            $scope._event = {
                loadStationNo: {
                    click: function(op_no, {event}) {
                        $scope.$root.showQueryList({
                            header: [
                                {label:$filter('translate')('common.queryList.op_c'), code:'page_no'},
                                {label:$filter('translate')('common.queryList.op_n'), code:'page_name'}
                            ],
                            query: function(conditions, feedback){
                                $MMWService.pageNumberInfoGet(
                                    {
                                        form_name: 'PageNo_33',
                                        query_condition_info:[
                                            {column_name:'B.MASTERNO', query_mode:'0', value:config.setting.OperatingArea, merge_condition_model:'AND' }
                                        ]
                                    },
                                    function(data){
                                        var temp = $filter('filter')(data, {favourite:'1'});
                                        //var temp = data.page_number_info_get;
                                        if(temp && temp.length){
                                            feedback(temp);
                                        } else {
                                            $scope.$root.showConfirm($filter('translate')('B0502.msg.favorite_empty'), function(confirmDialog){
                                                confirmDialog.hide();
                                                $timeout(function(){
                                                    $scope._fn.favorite.click(function(){
                                                        $scope._event.loadStationNo.click();
                                                    })
                                                }, 200);
                                            });
                                        }
                                    }
                                );
                            },
                            selectCode:$scope.condition.op_no||'',
                            confirm : function(selectItem, dialog){
                                //$scope.inspectionInfo.station_no = selectItem.page_no;
                                $scope.condition.op_display = selectItem.page_no + ' ('+selectItem.page_name+')';
                                $scope.condition.op_no = selectItem.page_no;
                                $scope.condition.op_name = selectItem.page_name;
                                $scope.condition.machine_no = selectItem.page_no;
                                $scope.condition.plot_no = '';
                                $scope.inspectionInfo = undefined;
                                localStorage.setItem(config.appName + '_B0502_favourite_op_no', JSON.stringify({op_no:$scope.condition.op_no, op_name:$scope.condition.op_name}));
                                dialog.hide();
                            }
                        });
                    }
                },
                plot_no: {
                    click: function(plot_no, {event}) {
                        if ($scope.condition.op_no != '') {
                            $MMWService.showQueryListPNIG({
                                form_name: 'PageNo_22',
                                condition: [
                                    {name:$filter('translate')('common.queryList.plot_no'), column_name:'LotNo', query_mode:'2', value:''}
                                ],
                                header: [
                                    {label:$filter('translate')('common.queryList.plot_no'), code:'page_no'}
                                ],
                                selectCode:$scope.condition.plot_no,
                                setCondition:function(conditions){
                                    conditions.push({column_name:'status', query_mode:'0', value:'0', merge_condition_model:'and'});
                                    conditions.push({column_name:'status', query_mode:'0', value:'1', merge_condition_model:'and'});
                                    if($scope.condition.op_no != '')
                                        conditions.push({column_name:'OPNo', query_mode:'2', value:$scope.condition.op_no });
                                    return conditions;
                                },
                                confirm : function(selectItem){
                                    $scope.condition.plot_no = selectItem.page_no;
                                    $scope.search();
                                }
                            });
                        }
                        else {
                            $scope.$root.showAlert($filter('translate')('B0502.msg.op_no_empty'));
                        }
                    }
                },
                employee_no: {
                    click() {
                        $scope.inspectionInfo.legal_employee_no = false;
                    }
                },
                machine_no: {
                    click() {
                        $MMWService.showQueryListPNIG({
                            form_name: 'PageNo_48',
                            condition: [
                                { name: $filter('translate')('common.queryList.machine_c'), column_name: 'BA.EQUIPMENTNO', query_mode: '2', value: '' }
                            ],
                            setCondition: function (conditions) {
                                conditions.push({ column_name: 'BA.OPID', query_mode: '0', value: $scope.condition.op_no, merge_condition_model: 'AND' });
                                return conditions;
                            },
                            header: [
                                { label: $filter('translate')('common.queryList.machine_c'), code: 'page_no' },
                                { label: $filter('translate')('common.queryList.machine_n'), code: 'page_name' }
                            ],
                            selectCode: $scope.inspectionInfo.machine_no,
                            confirm: function (selectItem) {
                                $scope.inspectionInfo.machine_no = selectItem.page_no;
                            }
                        });
                    }
                },
                work_machine: {
                    click() {
                        $MMWService.pageNumberInfoGet({
                            form_name: 'PageNo_49',
                            query_condition_info: [{ column_name: 'b.OPNO', query_mode: '0', value: $scope.condition.op_no, merge_condition_model: 'AND' }]
                        }, function (response) {
                            $scope.showSelect({
                                title: $filter('translate')('common.msg.plz_select'),
                                label: function (item) {
                                    return item.page_no;
                                },
                                code: 'page_no',
                                selectCode: $scope.inspectionInfo.work_machine,
                                list: response,
                                confirm: function (selected, d) {
                                    d.hide();
                                    $scope.inspectionInfo.work_machine = selected.page_no;
                                }
                            });
                        })
                    }
                },
                inspection_info: {},
                pcs_no: {}
            };

            $scope.switchJY = function (info) {
                $scope.qc_page = info;
                // 清空
                $scope.inspectionInfo = undefined;
                $scope.condition.plot_no = '';
                $scope.picSrcArray = [];
            };


            function beforeSaveFavorite(favoriteList, callback){
                var isDeleteCurrentOp = false;
                if($scope.condition.op_no && $scope.condition.op_no != ''){
                    if(favoriteList && favoriteList.length > 0){
                        var filterList = $filter('filter')(favoriteList, {op_no: $scope.condition.op_no}, true);
                        if(filterList.length == 0){
                            isDeleteCurrentOp = true; //使用者將"目前的作業站"從我的最愛移除了
                        }
                    }
                }

                if(isDeleteCurrentOp){
                    $scope.$root.showAlert($filter('translate')('B0502.msg.favorite_remove'),function(){
                        $scope.condition.op_no = '';
                        $scope.condition.op_name = '';
                        $scope.condition.machine_no = '';
                        $scope.condition.op_display = '';
                        $scope.condition.plot_no = '';
                        $scope.inspectionInfo = undefined;
                        localStorage.setItem(config.appName + '_B0502_favourite_op_no', JSON.stringify({op_no:$scope.condition.op_no, op_name:$scope.condition.op_name}));
                        if(callback)
                            callback();
                    });
                }else{
                    if(callback)
                        callback();
                }
            }

            $scope.confirm = function () {
                var defect_qty = 0, msg = '';
                //20200831 modify by Dustdusk for M#77210:
                $scope.inspectionInfo.qc_reason_detail.forEach(function(item, index){
                    //此項目須判斷是否要輸入不良
                    // 20231221 modify by wenwei for M#153794: [MSSQL] [H5][首巡自末检]质量检验检验项目不合格是否需要录入不良问题
                    if(item.is_inputscrap == '1'){
                        // switch btn 沒選過 / false
                        if(item.check_type == 0 && (item.reason_value == '' || item.reason_value == 'false')){
                            // 檢查不良現象是否有新增不良原因
                            if(dialog.inspectionInfo.checklist_detail.length == 0){
                                msg += $filter('translate')('B0207.check_list.column1') + item.reason_no + '、';
                            }
                        } else if(item.check_type == 1){
                            // 有輸入值
                            if(item.reason_value !== '' && item.reason_value !== null) {
                                // 符合標準
                                if((+item.mini_value) <= (+item.reason_value) && (+item.reason_value) <= (+item.max_value)) return
                            }
                            // 檢查不良現象是否有新增不良原因
                            if(dialog.inspectionInfo.checklist_detail.length == 0){
                                msg += $filter('translate')('B0207.check_list.column1') + item.reason_no + '、';
                            }
                        }
                    }
                });

                if(msg != ''){
                    if($scope.inspectionInfo.checklist_detail.length == 0){
                        $scope.$root.showAlert(msg + $filter('translate')('B0207.msg.checkitem_need_badreason'));
                        return;
                    }
                }

                $scope.inspectionInfo.checklist_detail.forEach(function(item, index){
                    item.item_seq = index;
                    defect_qty = $calculater.decimalAdd(defect_qty, item.item_qty);
                });

                if ((+defect_qty) > (+$scope.inspectionInfo.check_qty)){
                    msg = $filter('translate')('B0502.msg.check_qty_lt_defect_qty');
                } else if($scope.inspectionInfo.legal_employee_no == false){
                    msg = $filter('translate')('B0502.msg.check_employee_error');
                }

                if (msg == ''){
                    $scope.inspectionInfo.defect_qty = defect_qty;
                    firstPieceCheckProcess();
                } else {
                    $scope.$root.showAlert(msg);
                }
            };

            var badCodeList = [];

            $scope.barcodeScan = function(event){
                if(event.keyCode == 13){
                    $scope.search();
                }
            }

            $scope.QRcodeScanner = function(){
                $scope.$root.OpenScanner({
                    after : function(result){
                        if(result.text && result.text!=''){
                            var temp = result.text.split(';');
                            if(temp.length>1){
                                $scope.condition.op_no = temp[1]||'';
                            }
                            if(temp.length>0){
                                $scope.condition.plot_no = temp[0]||'';
                            }
                            $scope.search();
                        }
                    },
                    exception: function(){
                        //目前裝置無法使用相機
                        $scope.$root.showAlert($filter('translate')('B0214.showAlert.column3'));
                    },
                    orientation : 'landscape'
                });
            }

            //查詢 - 確認
            $scope.search = function () {
                if ($scope.condition.op_no.length == 0 || $scope.condition.plot_no.length == 0) {
                    $scope.$root.showAlert($filter('translate')('B0502.msg.plot_no_empty'));
                } else {
                    //20180525 modify by 李栋 for mantis#0047129
                    $MMWService.pageNumberInfoGet({
                        form_name : 'PageNo_8',
                        query_condition_info : [
                            {column_name:'OPNo', query_mode:'0', value: $scope.condition.op_no }
                        ]
                    }, function(itemList){
                        badCodeList = itemList;
                        $scope.inspectionInfo = {};
                        $scope.inspectionInfo.check_time = new Date();

                        wip_plot_status_info_get({
                            plot_no:$scope.condition.plot_no,
                            op_no:$scope.condition.op_no
                        }, function(data){
                            $scope.inspectionInfo.qty = data.qty;
                            $scope.inspectionInfo.employee_no = config.cache.account;
                            $scope.inspectionInfo.legal_employee_no = true;
                            $scope.inspectionInfo.check_qty = 1;
                            $scope.inspectionInfo.area_no = data.area_no;
                            opqcreason_info_get({plot_no:$scope.condition.plot_no,op_no:$scope.condition.op_no}, function(data){
                                $scope.server_url = 'http://'+config.server.ip+':'+config.server.port;
                                //$scope.inspectionInfo.type = data.type;
                                $scope.inspectionInfo.area_no = data.area_no;
                                $scope.inspectionInfo.qc_reason_detail = data.qc_reason_detail||[];
                                $scope.inspectionInfo.checklist_detail = [];
                            });
                        });
                    });
                }
            };

            $scope.itemCheck = function (index, data) {
                if (data.checked == 'undefined' || data.checked == 'N') {
                    data.checked = 'Y';
                }
                else {
                    data.checked = 'N';
                }
            };

            //不良原因開窗
            $scope.loadInspectionReasonList = function (item) {
                $scope.$root.showQueryList({
                    key:'page_no',
                    selectCode:item?item.page_no:'',
                    header : [
                        {label: $filter('translate')('common.queryList.badReason_c'), code:'page_no'},
                        {label: $filter('translate')('common.queryList.badReason_n'), code:'page_name'}
                    ],
                    query: function(conditions, feedback){
                        feedback(badCodeList);
                    },
                    confirm: function (selectItem, radioDialog) {
                        if(item != undefined){
                            item.item_code = selectItem.page_no;
                            item.page_no = selectItem.page_no;
                            item.page_name = selectItem.page_name;
                        } else {
                            $scope.inspectionInfo.checklist_detail.push({
                                item_code: selectItem.page_no,
                                page_no : selectItem.page_no,
                                page_name : selectItem.page_name,
                                item_qty: 1,
                                item_seq: ''
                            });
                        }
                        radioDialog.hide();
                    }
                });
            };

            $scope.addRow = function () {
                $scope.loadInspectionReasonList();
            };

            $scope.removeRow = function (index) {
                $scope.inspectionInfo.checklist_detail.splice(index, 1);
            };

            $scope.input_defect_qty = function (event, item) {
                var target = event.currentTarget;
                angular.element(target).addClass('is-focus');
                $calculater.open(function (num, calDialog) {
                        angular.element(target).removeClass('is-focus');
                        calDialog.hide();
                        item.item_qty = num;
                        //$scope.inspectionInfo.defect_qty = $scope.inspectionInfo.defect_qty + parseInt(num) - parseInt(oriNum);

                    },
                    function (calDialog) {
                        angular.element(target).removeClass('is-focus');
                        calDialog.hide();
                    },
                    {
                        defaultNum: item.item_qty,
                        decimalLength: 3
                    });
            };

            $scope.InRange = function(item){
                if(!item) {
                    return false;
                }
                if(item.check_type == 1 && item.reason_value!=""){  // 20231214 modify by shiwl for M# 0152513: 利达机电，测试区。自检首检的检验项目默认合格与否标准部一致
                    if((+item.mini_value) <= (+item.reason_value)
                        && (+item.reason_value) <= (+item.max_value)){
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }
            };

            //送出結果
            function firstPieceCheckProcess() {
                var content = {
                    machine_no: $scope.inspectionInfo.machine_no ? $scope.inspectionInfo.machine_no : 'N/A',
                    station_no: $scope.condition.op_no,
                    pcsno: $scope.inspectionInfo.pcs_no,
                    op_no: $scope.condition.op_no,
                    plot_no: $scope.condition.plot_no,
                    creator: config.cache.account,
                    employee_no: $scope.inspectionInfo.employee_no,
                    area_no: $scope.inspectionInfo.area_no,
                    check_qty: $scope.inspectionInfo.check_qty,
                    defect_qty: $scope.inspectionInfo.defect_qty,
                    check_time: moment($scope.inspectionInfo.check_time).format('YYYY-MM-DD HH:mm:ss'),
                    qc_result: 'Y',
                    qc_type: $scope.qc_page == 'first_check' ? '-1' : ($scope.qc_page == 'last_check' ? '-4' : '-2'),
                    position_no: $scope.inspectionInfo.work_machine,
                    type: '2',
                    checklist_detail: $scope.inspectionInfo.checklist_detail,
                    image_detail: [],
                    qc_reason_detail: $scope.inspectionInfo.qc_reason_detail,
                    run_type: 1
                };

                if((+content.defect_qty) != 0)
                    content.qc_result = 'N';

                for(var i=0;i<$scope.picSrcArray.length;i++){
                    var picSrc = $scope.picSrcArray[i];
                    content.image_detail.push({
                        image_src:picSrc,
                        image_seq:i,
                        image_format:'jpg'
                    });
                }

                //20180503 modify by 李栋 for mantis#0046586
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.first_piece_check_process',
                    content: content,
                    success: function () {
                        //20180416 modify by 李栋 for mantis#0045407
                        $scope.$root.showToast($filter('translate')('common.msg.success'));
                        $scope.inspectionInfo.checklist_detail = []; //清除不良原因
                        $scope.inspectionInfo.qc_reason_detail = []; //清除检验项目
                        $scope.picSrcArray = []; //清除相片
                        $scope.inspectionInfo = undefined;
                        $scope.condition.plot_no = '';
                        //$scope.inspectionInfo.qc_reason_detail.forEach(function(item){
                        //    item.reason_value = '';//20200110 modify by 韋齊 for M#65870 頁面刷新不要出現false，故將'false'改為空值
                        //});
                    }
                });
            }

            //檢核檢驗數量，不可大於原始值
            $scope.input_check_qty = function(){
                var target = event.currentTarget;
                angular.element(target).addClass('is-focus');
                $calculater.open(
                    function(num,calcDialog){
                        if((+num) > (+$scope.inspectionInfo.qty)){
                            $scope.$root.showAlert($filter('translate')('B0502.msg.check_qty_gt')+$scope.inspectionInfo.qty);
                        } else {
                            calcDialog.hide();
                            angular.element(target).removeClass('is-focus');
                            $scope.inspectionInfo.check_qty = num;
                        }
                    },
                    function(calcDialog){
                        angular.element(target).removeClass('is-focus');
                        calcDialog.hide();
                    },
                    {
                        defaultNum : $scope.inspectionInfo.check_qty,
                        decimal : false
                    }
                );
            };

            //檢合與沒有檢合的display
            $scope.isCheck = function(legal_employee_no){
                if(legal_employee_no){
                    return 'green';
                }else{
                    return 'red';
                }
            };

            //檢核使用者
            $scope.check_employee_no = function(){
                $MMWService.sendToServer({
                    uri : 'ServicesSTD.Module_SYS.user_information_get',
                    content : {
                        employee_no : $scope.inspectionInfo.employee_no,
                        report_datetime:moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
                        machine_no:'A',
                        return_type : '00'
                    },
                    success : function(data){
                        if(data.employee_no != $scope.inspectionInfo.employee_no){
                            $scope.$root.showAlert($filter('translate')('B0502.msg.check_employee_error'));
                            $scope.inspectionInfo.legal_employee_no = false;
                        }
                        else{
                            $scope.inspectionInfo.legal_employee_no = true;
                        }
                    },
                    error: function(data){
                        $scope.$root.showAlert(data.Message);
                        $scope.inspectionInfo.legal_employee_no = false;
                    }
                });
            };

            function wip_plot_status_info_get(content, feedback){
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.wip_plot_status_info_get',
                    content: content,
                    success: function (data) {
                        // data = JSON.parse(data.Result);
                        if(data.details && data.details.length > 0){
                            if(feedback)
                                feedback(data.details[0]);
                        } else {
                            $scope.inspectionInfo = undefined;
                            $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                        }
                    }
                });
            }

            function opqcreason_info_get(content, feedback) {
                var type = $scope.qc_page == 'first_check' ? '0' : ($scope.qc_page == 'last_check' ? '4' : '2')
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.op_qcreason_info_get',
                    content: {
                        op_no: content.op_no,
                        lot_no: content.plot_no,
                        machine_no: '',
                        area_no: '',
                        type: type
                    },
                    success: function (data) {
                        if(feedback)
                            feedback(data);
                    }
                });
            }

            var picLimitNum = 5;
            $scope.picSrcArray = [];
            //拍照
            $scope.pic_add = function($event){
                if($scope.picSrcArray.length < picLimitNum){
                    if(typeof(navigator.camera) !== 'undefined'){
                        //回傳URI
                        navigator.camera.getPicture(
                            function(imageURI) {                      
                                if($scope.$root.compressImage)
                                {
                                    $scope.$root.compressImage(imageURI, 
                                        function(data){  
                                            $scope.picSrcArray.push(data);
                                            $scope.$apply();
                                            }); 
                                }
                                else
                                {
                                    $scope.picSrcArray.push(imageURI);
                                    $scope.$apply();
                                }
                                //$scope.data.scrollLeft = document.getElementById('img-tile-list').clientWidth;
                            },
                            function(message) {
                                //alert('Failed because: ' + message);
                            },
                            {
                                quality: 50,
                                destinationType: Camera.DestinationType.DATA_URL
                            }
                        );
                    } else if(window.nodeRequire){
                        //回傳URI
                        $scope.$root.FileDialog({
                            callback:function(fileList){
                                $scope.$root.showLoading();
                                $scope.$apply();
                                setTimeout(function(){
                                    if(fileList){
                                        if(fileList.length == 0){
                                            //
                                        } else if(($scope.picSrcArray.length + fileList.length) > picLimitNum){
                                            $scope.$root.showAlert($filter('translate')('B0502.msg.pic_limit', {num:picLimitNum}));
                                        } else {
                                            var fs = window.nodeRequire('fs');
                                            fileList.forEach(function(fileName){
                                                var image = fs.readFileSync(fileName);
                                                if(image)
                                                {                           
                                                    if($scope.$root.compressImage)
                                                    {
                                                        $scope.$root.compressImage(new Buffer(image).toString('base64'), 
                                                        function(data){$scope.picSrcArray.push(data)}); 
                                                    }
                                                    else
                                                    {
                                                        $scope.picSrcArray.push(new Buffer(image).toString('base64'))
                                                    }
                                                }
                                            });
                                        }
                                    }
                                    $scope.$root.hideLoading();
                                    $scope.$apply();
                                });
                            }
                        });
                    } else {
                        $scope.$root.showAlert($filter('translate')('common.msg.cant_use_camera'));
                    }
                } else {
                    $scope.$root.showAlert($filter('translate')('B0502.msg.pic_limit', {num:picLimitNum}));
                }
            };

            $scope.pic_delete = function(index){
                $scope.picSrcArray.splice(index,1);
            };

            $scope.pic_open = function(index){
                $gallery.show('#'+(index+1), 'data:image/jpeg;base64,'+$scope.picSrcArray[index], function(){});
            };

            $scope.open_checkPic = function(item){
                $gallery.show(item.reason_no, $scope.server_url+item.picture_path, function(){});
            };

        }
    ];
});
